package org.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.netty.client.handler.ClientHandler;
import org.netty.coder.decoder.DecoderHandler;
import org.netty.coder.encoder.EncoderHandler;
import org.netty.protocol.file.FileTransferProtocol;
import org.netty.utils.ProtocolUtils;
import org.netty.utils.file.MsgUtil;

import java.io.File;

public class TcpClient {

    private String ip;
    private int port;

    public void init() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.option(ChannelOption.AUTO_READ, true);

//            bootstrap.option(ChannelOption.SO_SNDBUF, 1024*1024*1024);

            bootstrap.handler(new ChannelInitializer() {
                @Override
                protected void initChannel(Channel ch) {
//                    ch.pipeline().addLast("logging", new LoggingHandler(LogLevel.INFO));
                    ch.pipeline().addLast(new EncoderHandler());
                    ch.pipeline().addLast(new DecoderHandler());
                    ch.pipeline().addLast(new ClientHandler());
                }
            });
            bootstrap.remoteAddress(ip, port);
            ChannelFuture future = bootstrap.connect().sync();
//            sendFileData(future.channel());
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public TcpClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        new TcpClient("127.0.0.1", 8777).init();
    }

    public void sendFileData(Channel channel){

        File file = new File("D:\\download\\ideaIU-2020.3.win.zip");
        FileTransferProtocol fileTransferProtocol = MsgUtil.buildRequestTransferFile(file.getAbsolutePath(), file.getName(), file.length());
        //发送信息；请求传输文件
        channel.writeAndFlush(ProtocolUtils.prtclInstance(fileTransferProtocol));

    }
}
